﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.IO.Compression;
using Bohdan.Arch.Messaging;
using Bohdan.IO;

namespace WPF_Testing_Application
{
    public class IOMessage : GeneralMessage
    {
        public override Guid TargetSubscriberId
        {
            get { return IOWorker._Id; }
        }

        public string Filename { get; set; }
    }

    public class IOWorker : GeneralMultiThreadedSubscriber
    {
        public override int NumberOfWorkerThreads
        {
            get { return Environment.ProcessorCount + 1; }
        }
        public readonly static Guid _Id = new Guid("{7FCB24D0-762B-484c-A5AC-628CC0C5C5A1}");
        public override Guid SubscriberId
        {
            get
            {
                return _Id;
            }
        }

        public override System.Threading.ThreadPriority WorkerThreadPriority
        {
            get {
                return System.Threading.ThreadPriority.Lowest;
            }
        }

        protected override void ProcessMessage(GeneralMessage msg)
        {
            IOMessage m = (IOMessage)msg;


            FileStream fs = null;
            try
            {
                fs = File.OpenRead(m.Filename);
                CountingStream cs = new CountingStream();
                MemoryStream ms = new MemoryStream();
                GZipStream gz = new GZipStream(cs, CompressionMode.Compress);
                const int bufsize = 0x10000;
                byte[] buf = new byte[bufsize];
                for (long pos = 0, len = fs.Length; pos < len; )
                {
                    int piece = (int)Math.Min(len - pos, bufsize);
                    fs.Read(buf, 0, piece);
                    gz.Write(buf, 0, piece);
                    pos += piece;
                }

                gz.Flush();

                m.Bus.PostMessageAsync(new UIMessage()
                    {
                        LogMessage = string.Format("File {0}: Original size = {1} Compressed size = {2}", m.Filename, fs.Length, cs.Length)
                    });
            }
            catch (Exception ex)
            {
                m.Bus.PostMessageAsync(new UIMessage()
                    {
                        LogMessage = "Exception: " + ex.Message
                    });
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }
}
